{% block import %}
from integration_core__runner import Runner
{% endblock %}


{% block account %}
{% if account_config.authType == "accessKey" %}
account = {
    "ak_id"     : {{ repr(account_config.akId) }},
    "ak_secret" : {{ repr(account_config.akSecret) }},
    "extra_tags": {
        "account_name": {{ repr(account_config.accountName) }},
        "account_id": {{ repr(account_config.accountId) }}
    }
}
{% endif %}
{% endblock %}

{% block collect_configs %}
collector_configs = {
    'regions': {{ repr(collector.regions) }}
}

monitor_configs = {
    'targets': [
        {
            'namespace': {{ repr(namespace) }},
            {% if collector.metrics %}
            'metrics'  : {{ repr(collector.metrics) }}
            {% else %}
            'metrics'  : []
            {% endif %}
        }
    ]
}
{% endblock %}

{% block filters%}
def filter_instance(instance):
    '''
    return True｜False
    '''
    {% if not collector.filters%}
    return True
    {% else %}
    {% for filter in collector.filters %}
    {% if filter.value %}
    {% if filter.option in ["=="] %}
    {% set value = filter.value %}
    {% elif  filter.option in ["in"] %}
    {% set value = filter.value.split(',') %}
    {% endif %}
    if {{ filter.key }}_v := instance.get({{ repr(filter.key) }}):
        if {{ filter.key }}_v {{filter.option}} {{repr(value)}}:
            return True

    {% endif %}
    {% endfor %}
    return False
    {% endif %}


def filter_metric(instance, namespace={{ repr(namespace) }}):
    '''
    return True｜False
    '''
    {% if not collector.filters %}
    return True
    {% else %}
    {% for filter in collector.filters %}
    {% if filter.value %}
    {% if filter.option in ["=="] %}
        {% set value = filter.value %}
    {% elif  filter.option in ["in"] %}
        {% set value = filter.value.split(',') %}
    {% endif %}
    if {{ filter.key }}_v := instance['tags'].get({{ repr(filter.key) }}):
        if {{ filter.key }}_v {{filter.option}} {{repr(value)}}:
            return True

    {% endif %}
    {% endfor %}
    return False
    {% endif %}
{% endblock %}

{% block run %}
@DFF.API('{{ dff_api_title }}', timeout=300, fixed_crontab='{{ dff_api_crontab }}')
def run():
    collectors = [
        {% if not collector.filters %}
        obj_main.DataCollector(account, collector_configs),
        monitor_main.DataCollector(account, monitor_configs)
        {% else %}
        obj_main.DataCollector(account, collector_configs, filters=[filter_instance]),
        monitor_main.DataCollector(account, monitor_configs, filters=[filter_metric])
        {% endif %}
    ]
    Runner(collectors).run()
{% endblock %}
